<template>
    <div style="height: 100%" v-loading="loading">
        <van-nav-bar title="领料出库信息" left-text="返回" left-arrow @click-left="goBack" :right-text="postingDate"
            @click-right="setPostDate" />
        <van-calendar v-model="showCalendar" @confirm="onConfirm" :min-date="minDate" :max-date="maxDate" />
        <van-cell-group :v-model="tableData" style="
          overflow: scroll;
          height: 520px;
          ::-webkit-scrollbar {
            display: none;
          }
        ">
          <van-row>
            <van-field v-model="tableData.materialsnumber" label="领料单号" readonly />
          </van-row>
          <van-row>
            <van-field v-model="tableData.costcentername" label="成本中心" readonly />
          </van-row>
          <van-row>
            <van-field v-model="tableData.codeanddes" label="接收库位" readonly />
          </van-row>
          <van-row>
            <van-field v-model="tableData.internalordername" label="内部订单" readonly />
          </van-row>
          <van-row>
          <van-field v-model="tableData.name" label="领料人" readonly />
          </van-row>
          <van-row>
          <van-field v-model="tableData.materialno" label="物料" readonly />
          </van-row>
          <van-row>
          <van-field v-model="tableData.materialdes" label="物料描述" readonly />
          </van-row>
          <van-row>
            <van-col span="12">
              <van-field v-model="tableData.quantrequired" label="需求数量" readonly />
            </van-col>
            <van-col span="12">
              <van-field v-model="tableData.confirmed" label="已出数量" readonly />
            </van-col>
          </van-row>

          <van-field style="border: solid 1px #3793fb; border-radius: 5px" v-model="material_input" ref="material_input"
                     placeholder="请扫描物料" left-icon="scan" @input="onScanMaterialCode" />
          <van-swipe @change="onChangeMaterial" width="100%" ref="swiperMaterial" style="border: solid #3793fb 1px;border-top:none">
            <van-swipe-item v-for="(item, index) in tableData.details" :key="index">
              <van-field v-model="item.batchno" label="SAP批次" readonly></van-field>
              <van-field v-model="item.packinglotno" label="包装批" readonly></van-field>
              <van-field v-model="item.productionlotno" label="生产批" readonly></van-field>
              <van-field v-model="item.supplierbatchno" label="供应商批次" readonly></van-field>
              <van-field v-model="item.batchnoquant" label="本批次数量：" @input="quantityChange(1)" v-if="dc_flag != 'X'" ></van-field>
              <van-row style="border: solid 1px #3793fb; border-radius: 5px">
                <van-col span="24">
                  <el-autocomplete id="autocomplete" v-model="item.locationfrom" value-key="codeanddes" @input="onInput"
                                   label="发出库位" :rules="{ required: true, message: '请选择库位', trigger: 'blur',
                  }" :fetch-suggestions="storageLocationSearch" placeholder="发出库位" style="width: 100%;"></el-autocomplete>
                </van-col>
              </van-row>
              <van-button @click="onDeleteItem(index,1)" class="custom-swipe-delete" v-if="currentMaterial >= 0 && dc_flag != 'X'"
                          color="linear-gradient(to right, #ff6034, #ee0a24)">
                删除
              </van-button>
            </van-swipe-item>
            <template #indicator v-if="dc_flag != 'X'" >
              <div class="custom-indicator" v-if="currentMaterial >= 0">{{ currentMaterial + 1 }}/{{ totalSizeMaterial }}</div>
            </template>
          </van-swipe>

          <van-row>
            <van-field v-model="tableData.realquantity" label="实发数量" />
          </van-row>

          <van-field style="border: solid 1px #3793fb; border-radius: 5px" v-model="code_input" ref="code_input"
              placeholder="请扫描吨槽码" left-icon="scan" @input="onScanBarrelCode" v-if="dc_flag == 'X'" />
          <van-swipe @change="onChangeBucket" width="100%" ref="swiperBucket" style="border: solid #3793fb 1px;border-top:none">
              <van-swipe-item v-for="(item, index) in tableData.bucket" :key="index">
                  <van-field v-model="item.numberOfBarrels" label="桶号" readonly></van-field>
                  <van-field v-model="item.quantity" label="每桶数量" @input="quantityChange(2)"></van-field>
                  <van-button @click="onDeleteItem(index,2)" class="custom-swipe-delete" v-if="currentBucket >= 0"
                      color="linear-gradient(to right, #ff6034, #ee0a24)">
                      删除
                  </van-button>
              </van-swipe-item>
              <template #indicator>
                  <div class="custom-indicator" v-if="currentBucket >= 0">{{ currentBucket + 1 }}/{{ totalSizeBucket }}</div>
              </template>
            </van-swipe>
        </van-cell-group>
        <van-button @click="dialogVisible = true" style="
          position: fixed;
          bottom: 0px;
          border: #3793fb solid 1px;
          border-radius: 2px;
          background-color: #3793fb;
          line-height: var(--footer-height);
        " type="primary" block>领料出库</van-button>
      <el-dialog
          title="是否领料出库"
          :visible.sync="dialogVisible"
          width="70%">
        <span>确定成品领料出库?</span>
        <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="onSubmit">确 定</el-button>
  </span>
      </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
          dialogVisible: false,
          tableData: {
            details: [
            ],
            bucket: [
            ],
          },
          storageLocationList: [],
          loading: false,
          totalSizeMaterial: 0,
          totalSizeBucket: 0,
          currentMaterial: -1,
          currentBucket: -1,
          code_input: '',
          material_input: '',
          showCalendar: false,
          postingDate: this.getNowFormatDate(new Date()),
          minDate: this.getMonthBeforeDate(),
          maxDate: this.getMonthAfterDate(),
          specification: 0,
          dc_flag: false
      };
    },
    mounted() {
      //领料单信息
      this.getProductOutboundInfo(this.$route.query.codeInfo);
      //获取库位List
      this.getStorageLocationList();
    },
    methods: {
      async getProductOutboundInfo(codeInfo) {
        let scanInfo = {
          "CODE": codeInfo,
          "PLANT": localStorage.getItem("plant")
        }
        const {data: res} = await this.$http.post(
            "/MaterialsStorageNumber",
            scanInfo
        );
        this.tableData = res[0];
        this.tableData.details = [];
        this.tableData.bucket = [];
      },
      //返回
      goBack() {
        this.$router.push({
          path: "/ScanView",
          query: { title: '成品出库领料单扫描',key:5 },
        });
      },
      onScanMaterialCode(event) {
        this.getBucket(event,1);
      },
      onScanBarrelCode(event) {
        this.getBucket(event,2);
      },
      async getBucket(bucketNo,type) {
        if(1 === type){
          //扫描物料
          let scanInfo = {
            "code": bucketNo + ',' + localStorage.getItem("plant"),
            "RSNUM": this.tableData.materialsnumber
          };
          const { data: res } = await this.$http.post(
              "/MaterialsStorageMateriel",
              scanInfo
          );
          if(this.dc_flag == 'X' && this.tableData.details.length > 0 ){
            this.tableData.details = [];
            this.tableData.bucket = [];
            this.material_input = '';
            this.dc_flag = res[0].zifdc;
            this.specification = res[0].specification;
            this.tableData.materialno = res[0].materialno;
            this.tableData.materialdes = res[0].materialdes;
            this.tableData.quantrequired = res[0].quantrequired;
            this.tableData.confirmed = res[0].confirmed;
            this.tableData.realquantity = res[0].realquantity;
            this.tableData.details.push(res[0]);
            this.totalSizeMaterial = this.tableData.details.length;
            this.currentMaterial = this.totalSizeMaterial - 1;
            this.$refs.swiperMaterial.swipeTo(this.currentMaterial);
            console.log("不允许扫描多个物料.details",this.tableData.details);
          }else{
            if (res.length && res[0].materialno && res[0].batchno) {
              if(res[0].zifdc === 'X' && this.tableData.details.length > 0){
                this.$message({
                  message: "扫描失败，不允许同时扫描成品和辅料",
                  type: "error",
                });
                this.material_input = '';
                return
              }
              var keyNew = res[0].materialno + res[0].batchno;
              for (let i in this.tableData.details) {
                var key = this.tableData.details[i].materialno + this.tableData.details[i].batchno;
                if(keyNew === key){
                  this.$message({
                    message: "扫描失败，请勿重复扫描同一物料",
                    type: "error",
                  });
                  this.material_input = '';
                  return
                }
              }
              this.material_input = '';
              this.dc_flag = res[0].zifdc;
              this.specification = res[0].specification;
              this.tableData.materialno = res[0].materialno;
              this.tableData.materialdes = res[0].materialdes;
              this.tableData.quantrequired = res[0].quantrequired;
              this.tableData.confirmed = res[0].confirmed;
              this.tableData.realquantity = res[0].realquantity;
              this.tableData.details.push(res[0]);
              this.storageLocationList = res[0].stocks;
              this.totalSizeMaterial = this.tableData.details.length;
              this.currentMaterial = this.totalSizeMaterial - 1;
              this.$refs.swiperMaterial.swipeTo(this.currentMaterial);
              console.log("this.tableData.details",this.tableData.details);
            } else {
              this.material_input = '';
              this.$toast.fail('条码信息错误');
            }
          }
        }else if(2 === type){
          //扫描桶
          let scanInfo = {
            code: bucketNo,
          };
          const { data: res } = await this.$http.post(
              "/ProductionVerifyBucket",
              scanInfo
          );
          if (res.length && res[0].bucketnumber) {
            var requestData = this.tableData;
            for (var i in requestData.bucket) {
              if(requestData.bucket[i].numberOfBarrels === res[0].bucketnumber){
                this.$message({
                  message: "扫描失败，请勿重复扫描同一桶号",
                  type: "error",
                });
                this.code_input = '';
                return
              }
            }
            if('占用' !== res[0].bucketstatus && '领用' !== res[0].bucketstatus){
              this.$toast.fail('条码信息错误,非占用状态');
              this.code_input = '';
              return
            }
            var specification = this.specification;
            this.tableData.bucket.push({ numberOfBarrels: res[0].bucketnumber, quantity: specification });
            this.tableData.realquantity = parseInt(this.tableData.realquantity) + parseInt(specification);
            this.totalSizeBucket = this.tableData.bucket.length;
            this.currentBucket = this.totalSizeBucket - 1;
            this.$refs.swiperBucket.swipeTo(this.currentBucket);
            this.code_input = '';
          } else {
            this.code_input = '';
            this.$toast.fail('条码信息错误');
          }
        }
      },
      quantityChange(type) {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.changeQty(type);
        }, 0);
      },
      changeQty(type){
        var total = 0;
        if(type === 1){
          //物料
          for (let i in this.tableData.details) {
            if (this.tableData.details[i].batchnoquant !== '') {
              total += parseInt(this.tableData.details[i].batchnoquant);
            }
          }
        }else{
          //桶号
          for (let i in this.tableData.bucket) {
            if (this.tableData.bucket[i].quantity !== '') {
              total += parseInt(this.tableData.bucket[i].quantity);
            }
          }
        }
        this.tableData.realquantity = total;
      },
      onChangeMaterial(index) {
        this.currentMaterial = index;
      },
      onChangeBucket(index) {
        this.currentBucket = index;
      },
      onDeleteItem(index,type) {
        if(1 === type){
          //删除物料
          this.tableData.details.splice(index, 1);
          this.totalSizeMaterial = this.tableData.details.length;
          if (this.currentMaterial > this.totalSizeMaterial - 1) {
            this.currentMaterial = this.totalSizeMaterial - 1;
          }
          this.$refs.swiperMaterial.swipeTo(this.currentMaterial);
          if(this.dc_flag == 'X'){
            //如果带扫描的桶则清空
            this.tableData.bucket = [];
            this.totalSizeBucket = 0;
            this.currentBucket = -1;
            this.tableData.realquantity = 0;
          }else{
            this.tableData.realquantity -= this.tableData.details[index].batchnoquant;
          }
        }else if(2 === type){
          //删除桶
          this.tableData.realquantity -= this.tableData.bucket[index].quantity;
          this.tableData.bucket.splice(index, 1);
          this.totalSizeBucket = this.tableData.bucket.length;
          if (this.currentBucket > this.totalSizeBucket - 1) {
            this.currentBucket = this.totalSizeBucket - 1;
          }
          this.$refs.swiperBucket.swipeTo(this.currentBucket);
        }
      },
      onInput(value) {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          console.log('输入的内容是：', value);
        }, 0);
      },
      //库位搜索帮助
      storageLocationSearch(queryString, cb) {
        var storageLocationList = this.storageLocationList;
        var results = queryString
            ? storageLocationList.filter(this.createFilter(queryString))
            : storageLocationList;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        return (storageLocation) => {
          return (
              storageLocation.codeanddes
                  .toLowerCase()
                  .indexOf(queryString.toLowerCase()) !== -1
          );
        };
      },
      async getStorageLocationList() {
        let scanInfo = {
          plant: localStorage.getItem("plant"),
        };
        const { data: res } = await this.$http.post(
            "/StorageLocationList",
            scanInfo
        );
        this.storageLocationList = res;
      },
      getNowFormatDate(date) {
        let
            year = date.getFullYear(), //获取完整的年份(4位)
            month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
            strDate = date.getDate() // 获取当前日(1-31)
        if (month < 10) month = `0${month}` // 如果月份是个位数，在前面补0
        if (strDate < 10) strDate = `0${strDate}` // 如果日是个位数，在前面补0
        return `${year}-${month}-${strDate}`
      },
      setPostDate() {
        this.showCalendar = true;
      },
      onConfirm(date) {
        this.showCalendar = false;
        this.$dialog.confirm({
          title: '过账日期',
          message: '此选择将更改ERP过账日期',
        })
            .then(() => {
              this.postingDate = this.getNowFormatDate(date);
            })
            .catch(() => {
            });
      },

      //领料出库
      onSubmit() {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.postRawMaterialOutbound();
        }, 1000);
        this.dialogVisible = false;
      },

      //过账接口
      async postRawMaterialOutbound() {
        var requestData = this.tableData;
        var specification = this.specification;
        if (specification == '') {
          specification = 1;
        }
        var materialsList = [];
        if(this.dc_flag == 'X' ){
          for (let i in requestData.details) {
            materialsList.push({
              materialNo: requestData.materialno,
              materialDes: requestData.materialdes,
              quantRequired:requestData.quantrequired,
              confirmed:requestData.confirmed,
              realQuantity:requestData.realquantity,
              plant:requestData.details[i].plant,
              batchNo:requestData.details[i].batchno,
              packingLotNo:requestData.details[i].packinglotno,
              productionLotNo:requestData.details[i].productionlotno,
              supplierBatchNo:requestData.details[i].supplierbatchno,
              locationFrom:requestData.details[i].locationfrom,
              batchNoQuant:requestData.realquantity,
              specification:this.specification,
              zifdc:this.dc_flag,
            });
          }
        }else{
          for (let i in requestData.details) {
            materialsList.push({
              materialNo: requestData.materialno,
              materialDes: requestData.materialdes,
              quantRequired:requestData.quantrequired,
              confirmed:requestData.confirmed,
              realQuantity:requestData.realquantity,
              plant:requestData.details[i].plant,
              batchNo:requestData.details[i].batchno,
              packingLotNo:requestData.details[i].packinglotno,
              productionLotNo:requestData.details[i].productionlotno,
              supplierBatchNo:requestData.details[i].supplierbatchno,
              locationFrom:requestData.details[i].locationfrom,
              batchNoQuant:requestData.details[i].batchnoquant,
              specification:this.specification,
              zifdc:this.dc_flag,
            });
          }
        }
        var bucket = [];
        for (let i in requestData.bucket) {
          bucket.push({
            numberOfBarrels: requestData.bucket[i].numberOfBarrels,
            quantity:
            requestData.bucket[i].quantity,
          });
        }
        let inputInfo = {
          plant: localStorage.getItem("plant"),
          materialsNumber: requestData.materialsnumber,
          costCenter: requestData.costcenter,
          costCenterName: requestData.costcentername,
          codeanddes: requestData.codeanddes,
          location: requestData.codeanddes.split("|")[0],
          locationDes: requestData.codeanddes.split("|")[1],
          internalOrder: requestData.internalorder,
          internalOrderName: requestData.internalordername,
          postDate: this.postingDate,
          userName: requestData.username,
          name: requestData.name,
          bucket: bucket,
          materialsList: materialsList,
        };
        console.log("inputInfo",inputInfo)
        const { data: res } = await this.$http.post(
            "/PostMaterialsStorageMateriel",
            inputInfo
        );
        var response = res[0];
        console.log("res",response)
        if (response.type == "S") {
          this.$toast.success(response.message);
          this.getProductOutboundInfo(this.$route.query.codeInfo);
          this.totalSizeMaterial = 0;
          this.totalSizeBucket = 0;
          this.currentMaterial = -1;
          this.currentBucket = -1;
        } else if (response.type == "E") {
          this.$message({
            message: response.message,
            type: "error",
          });
        } else {
          this.$message({
            message: "出库失败，请联系系统维护人员",
            type: "error",
          });
        }
      },

    },
}
</script>

<style>
.el-input__inner {
    border: 0px;
    outline: none;
}
</style>